#include "task_UI.h"

#include "dialog_main.h"
#include "dialog_cali.h"
#include "dialog_startup.h"
#include "task_system.h"
#include "task_audio.h"
#include "task_key.h"
#include "task_mix.h"
#include "FreeRTOS.h"
#include "task.h"
#include "ee_driver.h"

/// global dialogs
MainDialog *pMainDialog=0;
CaliDialog *pCaliDialog=0;
StartupDialog *pStartupDialog =0;




void hardwareCheck()
{
    /// create lock for file
    fileSemaHandle =xSemaphoreCreateMutex();

    /// create startup dialog to show current status
    pStartupDialog = new StartupDialog();
    pStartupDialog->create();
    
    /// check eefs and format eefs if not available
    pStartupDialog->setStatusText((char*)"checking EE file system");
    pStartupDialog->setStep(10);
    if(EE_OK !=eefs->check())
    {
        //play a beep 
        playBeep(2000, 100, 2);

        /// show eefs fault status
        pStartupDialog->setStatusText((char*)"EE file system error, formating...");
        eefs->format();

        pStartupDialog->setStatusText((char*)"Creating default files");
        //create default transmiter

        //create default model
    }

    pStartupDialog->setStep(50);
    pStartupDialog->setStatusText((char*)"reading working file");

    /// read transmiter
    EeFile ee_file;
    eefs->open(&ee_file, FILE_ID_TRANSMITER, EE_MODE_READ);
    if(eefs->readRLE(&ee_file, &transmiterFile, sizeof(transmiterFile), 0) !=sizeof(transmiterFile) )
    {
        eefs->close(&ee_file);

        setDefaultTransmiterFile();
        setDefaultModelFile();
        eefs->open(&ee_file, FILE_ID_TRANSMITER, EE_MODE_WRITE);
        eefs->writeRLE(&ee_file, &transmiterFile, sizeof(transmiterFile), 0);
        eefs->close(&ee_file);

        eefs->open(&ee_file, 0, EE_MODE_WRITE);
        eefs->writeRLE(&ee_file, &modelFile, sizeof(modelFile), 0);
        
    }
    eefs->close(&ee_file);


    /// read model
    eefs->open(&ee_file, transmiterFile.currModel, EE_MODE_READ);
    eefs->readRLE(&ee_file, &modelFile, sizeof(modelFile), 0);
    eefs->close(&ee_file);
    
    pStartupDialog->setStep(100);
    pStartupDialog->setStatusText((char*)"OK");

    delete pStartupDialog;

    pStartupDialog =0;

    /// start taskSystem;
    xTaskCreate(taskSystem, (const signed char *)"taskSystem", TASK_SYSTEM_STACK_SIZE, NULL, 2, NULL);
}

void taskUI(void *pdata)
{
    //create Gdi device
    pGdi = new Gdi;
    //create message queue
    msgQue =new MsgQue;

    //create key task
    xTaskCreate(taskKey, (const signed char *)"taskKey", TASK_KEY_STACK_SIZE, NULL, 2, NULL);

    /// create eefs
    eefs =new EeFs(&ee_driver);

    hardwareCheck();

    /// for testing only

    //create the first dialog
    pMainDialog = new MainDialog;

    pMainDialog->run();
    delete pMainDialog;
    pMainDialog =0;
    
    while(1);
}

